<%@ page language="java" contentType="text/html; charset=utf-8" %>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page"/>
<jsp:useBean id="bb" class="weaver.general.BaseBean"/>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="org.apache.http.HttpEntity" %>
<%@ page import="org.apache.http.client.methods.CloseableHttpResponse" %>
<%@ page import="org.apache.http.client.methods.HttpPost" %>
<%@ page import="org.apache.http.config.Registry" %>
<%@ page import="org.apache.http.config.RegistryBuilder" %>
<%@ page import="org.apache.http.conn.socket.ConnectionSocketFactory" %>
<%@ page import="org.apache.http.conn.socket.PlainConnectionSocketFactory" %>
<%@ page import="org.apache.http.conn.ssl.SSLConnectionSocketFactory" %>
<%@ page import="org.apache.http.entity.ContentType" %>
<%@ page import="org.apache.http.entity.StringEntity" %>
<%@ page import="org.apache.http.entity.mime.HttpMultipartMode" %>
<%@ page import="org.apache.http.entity.mime.MultipartEntityBuilder" %>
<%@ page import="org.apache.http.impl.client.CloseableHttpClient" %>
<%@ page import="org.apache.http.impl.client.HttpClients" %>
<%@ page import="org.apache.http.impl.conn.PoolingHttpClientConnectionManager" %>
<%@ page import="org.apache.http.util.EntityUtils" %>
<%@ page import="weaver.alioss.AliOSSObjectManager" %>
<%@ page import="weaver.conn.ConnStatement" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.file.AESCoder" %>
<%@ page import="weaver.general.Base64" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="javax.net.ssl.SSLContext" %>
<%@ page import="javax.net.ssl.TrustManager" %>
<%@ page import="javax.net.ssl.X509TrustManager" %>
<%@ page import="java.io.*" %>
<%@ page import="java.nio.charset.Charset" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.Set" %>
<%@ page import="java.util.zip.ZipInputStream" %>
<%

    String id = Util.null2String(request.getParameter("id"));
    String tablename = "uf_xshttz";
    out.print(">>>>>>WeaSalesContractAction>>>>>" + id + "<br/>");
    try {
        rs.executeQuery("select gzhht,lcid,htbh from " + tablename + " where id=?", id);
        rs.next();
        String gzhht = Util.null2String(rs.getString("gzhht"));
        String lcid = Util.null2String(rs.getString("lcid"));
        String htbh = Util.null2String(rs.getString("htbh"));
        boolean wfStatus = hasWfStatus(lcid);
        out.print(">>>>>>WeaSalesContractAction>>>>>" + wfStatus + "<br/>");
        if (wfStatus) {
            rs.executeQuery("select imagefileid,imagefilename from DocImageFile where docid in (" + gzhht + ")");
            while (rs.next()) {
                int imagefileid = Util.getIntValue(rs.getString("imagefileid"), -1);
                String imagefilename = Util.null2String(rs.getString("imagefilename"));
                try {
                    InputStream inputStream = getInputStreamById(imagefileid);
                    byte[] byteArray = new byte[inputStream.available()];
                    inputStream.read(byteArray);
                    JSONObject jsonData = new JSONObject();
                    jsonData.put("companyCode", "01-0070-7919557180-C3973");
                    jsonData.put("contractCode", htbh);
                    jsonData.put("tenantCode", "ZWGK");
                    jsonData.put("contractClass", "XS");
                    jsonData.put("fileSec", "1702");
                    jsonData.put("fileType", "ZS");
                    jsonData.put("fileName", imagefilename);
                    jsonData.put("file", Base64.decode(byteArray));
                    out.print(">>>>>>jsonData>>>>>" + jsonData.toJSONString() + "<br/>");
                    String resultText = Invoke(jsonData.toJSONString());
                    out.print(">>>>>>resultText>>>>>" + resultText + "<br/>");
                    JSONObject resultJson = JSONObject.parseObject(resultText);
                    String code = Util.null2String(resultJson.getString("code"));
                    String data = Util.null2String(resultJson.getString("data"));
                    out.print("code=" + code + ",data=" + data);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        e.printStackTrace();
    }

%>
<%!

    public static final String URL = "http://172.22.2.3/transfer/laisiattach/LesCont/api/contFile/upload";

    public static String Invoke(String params) {
        Map<String, String> header = new HashMap<>();
        header.put("ContentType", "application/json");
        String ecode = "UTF-8";
        return httpPostRaw(URL, params, header, ecode);
    }

    /**
     * 发送 http post 请求，参数以原生字符串进行提交
     *
     * @param url
     * @param encode
     * @return
     */
    public static String httpPostRaw(String url, String stringJson, Map<String, String> headers, String encode) {
        if (encode == null) {
            encode = "utf-8";
        }
        String content = null;
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;
        try {

            //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
            closeableHttpClient = HttpClients.createDefault();
            HttpPost httpost = new HttpPost(url);

            //设置header
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
            mEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            mEntityBuilder.setCharset(Charset.forName(encode));

            //组织请求参数
            StringEntity stringEntity = new StringEntity(stringJson, encode);
            httpost.setEntity(stringEntity);


            //响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

    //发送 http post 请求，支持文件上传
    public static String httpPostFormMultipart(String url, Map<String, String> params, File file, Map<String, String> headers, String encode) {
        if (encode == null) {
            encode = "utf-8";
        }
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;
        String content = null;
        //since 4.3 不再使用 DefaultHttpClient
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) {
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            sslcontext.init(null, new TrustManager[]{trustManager}, null);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslcontext)).build();
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            HttpClients.custom().setConnectionManager(connManager);
            closeableHttpClient = HttpClients.createDefault();
            HttpPost httpost = new HttpPost(url);

            //设置header
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
            mEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            mEntityBuilder.setCharset(Charset.forName(encode));

            // 普通参数
            ContentType contentType = ContentType.create("text/plain", Charset.forName(encode));//解决中文乱码
            if (params != null && params.size() > 0) {
                Set<String> keySet = params.keySet();
                for (String key : keySet) {
                    mEntityBuilder.addTextBody(key, params.get(key), contentType);
                }
            }
            //二进制参数

            mEntityBuilder.addBinaryBody("file", file);
            httpost.setEntity(mEntityBuilder.build());
            httpResponse = closeableHttpClient.execute(httpost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

    //返回文件流   已经经过脱密、解压
    public static InputStream getInputStreamById(int imageFileId) {
        InputStream imagefile = null;
        try {
            RecordSet rs = new RecordSet();
            String sql = "select fileRealPath,isZip,isaesencrypt,aescode,tokenKey,storageStatus  from ImageFile where imageFileId = (select imagefileid from docimagefile where docid ='" + imageFileId + "')";
            rs.executeQuery(sql);
            if (rs.next()) {
                String static_fileRealPath = Util.null2String(rs.getString("fileRealPath"));
                String static_isZip = Util.null2String(rs.getString("isZip"));
                int static_isaesencrypt = Util.getIntValue(rs.getString("isaesencrypt"), 0);
                String static_aescode = Util.null2String(rs.getString("aescode"));
                String static_tokenKey = Util.null2String(rs.getString("tokenKey"));
                String static_storageStatus = Util.null2String(rs.getString("storageStatus"));
                boolean isonlyAliOSS = false;
                if (!static_tokenKey.equals("") && static_storageStatus.equals("1") && AliOSSObjectManager.isonlyAliOSS()) {
                    isonlyAliOSS = true;
                }

                if (isonlyAliOSS) {
                    imagefile = weaver.alioss.AliOSSObjectUtil.downloadFile(static_tokenKey);
                } else {
                    if (static_fileRealPath != null && !static_fileRealPath.equals("")) {
                        File thefile = new File(static_fileRealPath);
                        if (static_isZip.equals("1")) {
                            ZipInputStream zin = new ZipInputStream(new FileInputStream(thefile));
                            if (zin.getNextEntry() != null) {
                                imagefile = new BufferedInputStream(zin);
                            }
                        } else {
                            imagefile = new BufferedInputStream(new FileInputStream(thefile));
                        }
                    } else {
                        ConnStatement statement = null;
                        try {
                            statement = new ConnStatement();
                            boolean isoracle = ("oracle").equals(statement.getDBType());
                            statement.setStatementSql("select imagefile from ImageFile where imagefileid = " + imageFileId);
                            statement.executeQuery();
                            if (statement.next()) {
                                if (isoracle) {
                                    imagefile = new BufferedInputStream(statement.getBlobBinary("imagefile"));
                                } else {
                                    imagefile = new BufferedInputStream(statement.getBinaryStream("imagefile"));
                                }
                            }
                        } catch (Exception ex) {
                        } finally {
                            try {
                                if (statement != null) {
                                    statement.close();
                                }
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                    if (static_isaesencrypt == 1) {
                        imagefile = AESCoder.decrypt(imagefile, static_aescode);
                    }

                }
            }


        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return imagefile;
    }

    public static boolean hasWfStatus(String requestid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select count(requestid) from workflow_requestbase where requestid=? and currentnodetype=3", requestid);
        rs.next();
        return Util.getIntValue(rs.getString(1)) > 0;
    }

%>